<template>
  <div class="job-detail">
    <!-- 头部导航 -->
    <header class="header">
      <div class="container">
        <div class="logo">
          <router-link to="/" class="logo-link">
            <h1>伟邦人才信息网</h1>
          </router-link>
        </div>
        <nav class="nav">
          <router-link to="/" class="nav-item">首页</router-link>
          <router-link to="/login" v-if="!userStore.isLoggedIn" class="nav-item">登录</router-link>
          <router-link to="/user" v-if="userStore.isLoggedIn" class="nav-item">个人中心</router-link>
          <router-link to="/admin" v-if="userStore.isAdmin" class="nav-item">管理后台</router-link>
          <el-button v-if="userStore.isLoggedIn" @click="logout" type="text">退出</el-button>
        </nav>
      </div>
    </header>

    <!-- 岗位详情内容 -->
    <div class="detail-content" v-if="job">
      <div class="container">
        <div class="detail-layout">
          <!-- 左侧详情 -->
          <div class="detail-main">
            <div class="job-header">
              <h1 class="job-title">{{ job.title }}</h1>
              <div class="job-meta">
                <span class="salary">{{ job.salary }}</span>
                <span class="location">{{ job.location }}</span>
                <span class="experience">{{ job.experience }}</span>
              </div>
            </div>

            <div class="company-info">
              <h3>公司信息</h3>
              <p class="company-name">{{ job.company }}</p>
              <p class="education">学历要求：{{ job.education }}</p>
            </div>

            <div class="job-description">
              <h3>岗位描述</h3>
              <p>{{ job.description }}</p>
            </div>

            <div class="job-requirements">
              <h3>任职要求</h3>
              <ul>
                <li v-for="(req, index) in job.requirementList" :key="index">
                  {{ req }}
                </li>
              </ul>
            </div>

            <div class="job-benefits">
              <h3>福利待遇</h3>
              <ul>
                <li v-for="(benefit, index) in job.benefitList" :key="index">
                  {{ benefit }}
                </li>
              </ul>
            </div>

            <!-- 岗位图片展示 -->
            <div class="job-images" v-if="job.images && job.images.length > 0">
              <h3>岗位图片</h3>
              <div class="image-gallery">
                <el-carousel 
                  :interval="4000" 
                  type="card" 
                  height="300px"
                  v-if="job.images.length > 1"
                >
                  <el-carousel-item v-for="(image, index) in job.images" :key="index">
                    <div class="carousel-image" @click="previewImage(image, job.images)">
                      <img :src="image.url" :alt="`岗位图片${index + 1}`" />
                    </div>
                  </el-carousel-item>
                </el-carousel>
                <div class="single-image" v-else @click="previewImage(job.images[0], job.images)">
                  <img :src="job.images[0].url" :alt="'岗位图片'" />
                </div>
              </div>
            </div>

            <!-- 岗位视频展示 -->
            <div class="job-videos" v-if="job.videos && job.videos.length > 0">
              <h3>岗位视频</h3>
              <div class="video-gallery">
                <div 
                  v-for="(video, index) in job.videos" 
                  :key="index" 
                  class="video-item"
                >
                  <h4>{{ video.name || `视频${index + 1}` }}</h4>
                  <video 
                    :src="video.url" 
                    controls 
                    preload="metadata"
                    class="video-player"
                  >
                    您的浏览器不支持视频播放
                  </video>
                </div>
              </div>
            </div>

            <!-- 相关文件展示 -->
            <div class="job-files" v-if="job.files && job.files.length > 0">
              <h3>相关文件</h3>
              <div class="file-list">
                <div 
                  v-for="(file, index) in job.files" 
                  :key="index" 
                  class="file-item"
                >
                  <div class="file-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="file-info">
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-size">{{ formatFileSize(file.size) }}</div>
                  </div>
                  <div class="file-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="downloadFile(file)"
                    >
                      <el-icon><Download /></el-icon>
                      下载
                    </el-button>
                    <el-button 
                      size="small" 
                      @click="previewFileHandler(file)"
                    >
                      <el-icon><View /></el-icon>
                      预览
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <div class="action-buttons">
              <el-button type="primary" size="large" @click="applyJob">
                立即申请
              </el-button>
              <el-button size="large" @click="shareJob">
                <el-icon><Share /></el-icon>
                分享岗位
              </el-button>
            </div>
          </div>

          <!-- 右侧分享信息 -->
          <div class="detail-sidebar">
            <div class="share-card">
              <h3>分享者信息</h3>
              <div class="share-user" v-if="shareUser">
                <div class="user-avatar">
                  <el-icon><User /></el-icon>
                </div>
                <div class="user-info">
                  <p class="user-name">{{ shareUser.nickName }}</p>
                  <p class="user-role">{{ shareUser.userRole === 'admin' ? '管理员' : '业务员' }}</p>
                </div>
              </div>
              
              <div class="contact-info">
                <div class="contact-item">
                  <el-icon><Phone /></el-icon>
                  <span>{{ shareUser?.phonenumber || '暂无' }}</span>
                </div>
                <div class="contact-item">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>{{ shareUser?.wechat || '暂无' }}</span>
                </div>
                <div class="contact-item">
                  <el-icon><Message /></el-icon>
                  <span>{{ shareUser?.email || '暂无' }}</span>
                </div>
              </div>

              <div class="share-stats">
                <div class="stat-item">
                  <span class="stat-number">{{ customerCount }}</span>
                  <span class="stat-label">已登记客户</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ shareCount }}</span>
                  <span class="stat-label">分享次数</span>
                </div>
              </div>
            </div>

            <div class="apply-card">
              <h3>快速申请</h3>
              <p>填写基本信息，我们会尽快与您联系</p>
              <el-button type="primary" @click="goToCustomerForm" block>
                填写申请表单
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享岗位信息" width="500px">
      <div class="share-content">
        <div class="share-info">
          <h4>{{ job?.title }}</h4>
          <p>{{ job?.company }} | {{ job?.location }} | {{ job?.salary }}</p>
        </div>
        
        <div class="share-link">
          <el-input
            :value="shareLink"
            readonly
            class="share-input"
          >
            <template #append>
              <el-button @click="copyShareLink">复制链接</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="share-options">
          <el-button @click="shareToWechat" type="success" block>
            <el-icon><ChatDotRound /></el-icon>
            分享到微信
          </el-button>
          <el-button @click="shareToQQ" type="primary" block>
            <el-icon><Message /></el-icon>
            分享到QQ
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 申请对话框 -->
    <el-dialog  :close-on-click-modal="false" v-model="applyDialogVisible" title="申请岗位" width="600px">
      <div class="apply-form">
        <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="applyForm.name" placeholder="请输入您的姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="applyForm.phone" placeholder="请输入您的手机号" />
          </el-form-item>
          <el-form-item label="微信号" prop="wechat">
            <el-input v-model="applyForm.wechat" placeholder="请输入您的微信号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="applyForm.email" placeholder="请输入您的邮箱" />
          </el-form-item>
          <el-form-item label="工作经验" prop="experience">
            <el-select v-model="applyForm.experience" placeholder="请选择工作经验">
              <el-option label="应届毕业生" value="应届毕业生" />
              <el-option label="1年以下" value="1年以下" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-5年" value="3-5年" />
              <el-option label="5年以上" value="5年以上" />
            </el-select>
          </el-form-item>
          <el-form-item label="期望薪资" prop="expectedSalary">
            <el-input v-model="applyForm.expectedSalary" placeholder="请输入期望薪资" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApply">提交申请</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :url-list="imageList"
      :initial-index="currentImageIndex"
      @close="imageViewerVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useJobsStore } from '@/stores/jobs'
import { mockJobs, mockUsers, mockCustomerRegistrations } from '@/mock/data'
import { ElMessage, ElImageViewer } from 'element-plus'
import { getPositionDetail, userGet, customersAdd } from "@/api/system"


const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const jobsStore = useJobsStore()

const job = ref(null)
const shareUser = ref(null)
const shareDialogVisible = ref(false)
const applyDialogVisible = ref(false)
const shareLink = ref('')
const applyFormRef = ref()

const applyForm = ref({
  name: '',
  phone: '',
  wechat: '',
  email: '',
  experience: '',
  expectedSalary: ''
})

const applyRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  wechat: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  experience: [{ required: true, message: '请选择工作经验', trigger: 'change' }],
  expectedSalary: [{ required: true, message: '请输入期望薪资', trigger: 'blur' }]
}

// 客户数量统计
const customerCount = computed(() => {
  if (!job.value) return 0
  return mockCustomerRegistrations.filter(reg => reg.jobId === job.value.id).length
})

// 分享次数统计
const shareCount = computed(() => {
  if (!job.value) return 0
  // 这里可以根据实际需求统计分享次数
  return Math.floor(Math.random() * 100) + 10
})

const getJobDetail = async (jobId) => {
  const userInfo = await getPositionDetail(jobId)

  if(userInfo.data.images && userInfo.data.images.length>0){
    userInfo.data.images = JSON.parse(userInfo.data.images)
  }
  if(userInfo.data.files && userInfo.data.files.length>0){
    userInfo.data.files = JSON.parse(userInfo.data.files)
  }
  if(userInfo.data.videos && userInfo.data.videos.length>0){
    userInfo.data.videos = JSON.parse(userInfo.data.videos)
  }
  job.value = userInfo.data
}
const getShareDetail = async (jobId,shareUserId) => {
  const userInfo = await userGet(shareUserId)
  shareUser.value = userInfo.data
  shareLink.value = `${window.location.origin}/job/${jobId}?shareUserId=${shareUserId}`
}

// 初始化数据
onMounted(() => {
  const jobId = parseInt(route.params.id)
//  const foundJob = mockJobs.find(j => j.id === jobId)
  if (jobId) {
    getJobDetail(jobId)
//    job.value = foundJob
//    jobsStore.setCurrentJob(foundJob)

    const shareUserId = route.query.shareUserId ? parseInt(route.query.shareUserId) : localStorage.getItem('user') && typeof localStorage.getItem('user') != 'string'? JSON.parse(localStorage.getItem('user'))?.userId : null
    if(shareUserId){
      getShareDetail(jobId,shareUserId)
    }
  } else {
    ElMessage.error('岗位信息不存在')
    router.push('/')
  }
})

// 申请岗位
const applyJob = () => {
  applyDialogVisible.value = true
}

// 分享岗位
const shareJob = () => {
  shareDialogVisible.value = true
}

// 复制分享链接
const copyShareLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

// 分享到微信
const shareToWechat = () => {
  ElMessage.success('已分享到微信')
  shareDialogVisible.value = false
}

// 分享到QQ
const shareToQQ = () => {
  ElMessage.success('已分享到QQ')
  shareDialogVisible.value = false
}

// 跳转到客户登记表单
const goToCustomerForm = () => {
  router.push(`/form/${job.value.positionId}?shareUserId=${shareUser.value?.userId}`)
}

// 提交申请
const submitApply = async () => {
  try {
    await applyFormRef.value.validate()
    
    // 模拟提交申请
    const registration = {
      id: Date.now(),
      jobId: job.value.positionId,
      shareUserId: shareUser.value?.userId || 1,
      customerName: applyForm.value.name,
      phone: applyForm.value.phone,
      wechat: applyForm.value.wechat,
      email: applyForm.value.email,
      experience: applyForm.value.experience,
      expectedSalary: applyForm.value.expectedSalary,
      registerTime: new Date().toLocaleString(),
      status: 'pending'
    }
    await customersAdd(registration)
//    jobsStore.addCustomerRegistration(registration)
    
    ElMessage.success('申请提交成功，我们会尽快与您联系！')
    applyDialogVisible.value = false
    
    // 重置表单
    applyForm.value = {
      name: '',
      phone: '',
      wechat: '',
      email: '',
      experience: '',
      expectedSalary: ''
    }
  } catch (error) {
    ElMessage.error('请完善申请信息')
  }
}

// 退出登录
const logout = () => {
  userStore.logout()
  router.push('/')
  ElMessage.success('已退出登录')
}

// 图片预览相关
const imageViewerVisible = ref(false)
const currentImageIndex = ref(0)
const imageList = ref([])

// 预览图片
const previewImage = (image, images) => {
  imageList.value = images.map(img => img.url)
  currentImageIndex.value = images.findIndex(img => img.url === image.url)
  imageViewerVisible.value = true
}

// 下载文件
const downloadFile = (file) => {
  const link = document.createElement('a')
  link.href = file.url
  link.download = file.name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('文件下载已开始')
}

// 预览文件
const previewFileHandler = (file) => {
  // 如果是图片文件，使用图片预览
  if (isImageFile(file.name)) {
    previewImage({ url: file.url }, [{ url: file.url }])
  } else {
    // 其他文件直接下载或在新窗口打开
    window.open(file.url, '_blank')
  }
}

// 判断是否为图片文件
const isImageFile = (filename) => {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg']
  return imageExtensions.some(ext => filename.toLowerCase().endsWith(ext))
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '未知大小'
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}
</script>

<style scoped>
.job-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-link {
  color: white;
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-item {
  color: white;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-item:hover {
  background-color: rgba(255,255,255,0.2);
}

/* 详情内容 */
.detail-content {
  padding: 40px 0;
}

.detail-layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

.detail-main {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.job-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.job-title {
  font-size: 28px;
  color: #333;
  margin: 0 0 15px 0;
}

.job-meta {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.salary {
  color: #e74c3c;
  font-weight: bold;
  font-size: 18px;
}

.location,
.experience {
  color: #666;
  font-size: 16px;
}

.company-info,
.job-description,
.job-requirements,
.job-benefits {
  margin-bottom: 30px;
}

.company-info h3,
.job-description h3,
.job-requirements h3,
.job-benefits h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.company-name {
  font-size: 16px;
  color: #666;
  margin: 0 0 10px 0;
}

.education {
  color: #666;
  margin: 0;
}

.job-description p {
  color: #666;
  line-height: 1.8;
  margin: 0;
}

.job-requirements ul,
.job-benefits ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.job-requirements li,
.job-benefits li {
  color: #666;
  line-height: 1.8;
  padding: 5px 0;
  position: relative;
  padding-left: 20px;
}

.job-requirements li::before,
.job-benefits li::before {
  content: '•';
  color: #667eea;
  position: absolute;
  left: 0;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

/* 岗位图片展示 */
.job-images {
  margin-bottom: 30px;
}

.job-images h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.image-gallery {
  width: 100%;
}

.carousel-image {
  width: 100%;
  height: 300px;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
}

.carousel-image:hover {
  transform: scale(1.02);
}

.carousel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.single-image {
  width: 100%;
  max-width: 600px;
  height: 400px;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
}

.single-image:hover {
  transform: scale(1.02);
}

.single-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 岗位视频展示 */
.job-videos {
  margin-bottom: 30px;
}

.job-videos h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.video-gallery {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.video-item h4 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 16px;
}

.video-player {
  width: 100%;
  max-width: 600px;
  height: auto;
  border-radius: 8px;
  background: #000;
}

/* 相关文件展示 */
.job-files {
  margin-bottom: 30px;
}

.job-files h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.3s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #667eea;
}

.file-icon {
  width: 40px;
  height: 40px;
  background: #667eea;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
  word-break: break-all;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.file-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

/* 侧边栏 */
.detail-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.share-card,
.apply-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.share-card h3,
.apply-card h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 16px;
}

.share-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  background: #667eea;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.user-name {
  font-weight: bold;
  color: #333;
  margin: 0 0 5px 0;
}

.user-role {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.contact-info {
  margin-bottom: 20px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
  margin-bottom: 10px;
  font-size: 14px;
}

.share-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.apply-card p {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 14px;
}

/* 分享对话框 */
.share-content {
  text-align: center;
}

.share-info {
  margin-bottom: 20px;
}

.share-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.share-info p {
  margin: 0;
  color: #666;
}

.share-link {
  margin-bottom: 20px;
}

.share-input {
  width: 100%;
}

.share-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.share-options .el-button{
    margin-left: 0;
}

/* 申请表单 */
.apply-form {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .header .container {
    flex-direction: column;
    gap: 15px;
  }
  
  .nav {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .detail-layout {
    grid-template-columns: 1fr;
  }
  
  .job-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .single-image {
    height: 300px;
  }
  
  .video-player {
    max-width: 100%;
  }
  
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .file-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 